<?php
declare(strict_types=1);

namespace Newbie\Middlewares;

use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

/**
 * 跨域中间件
 * Class AllowOriginMiddleware
 * @package app\middleware
 */
class AllowCrossMiddleware implements MiddlewareInterface {
    /**
     * @param Request $request
     * @param callable $handler
     * @return Response
     */
    public function process (Request $request, callable $handler): Response {
        $origin = $request->header('origin');
        if (!$origin) {
            $origin = 'http://localhost:5173';
        }
        $headers  = [
            'Access-Control-Allow-Credentials' => 'true',
            'Access-Control-Allow-Origin'      => $request->header('origin', $origin),
            'Access-Control-Allow-Methods'     => $request->header('access-control-request-method', '*'),
            'Access-Control-Allow-Headers'     => $request->header('access-control-request-headers', '*'),
        ];
        $response = strtoupper($request->method()) === 'OPTIONS' ? response('', 204) : $handler($request);
        // 给响应添加跨域相关的http头
        return $response->withHeaders($headers);
    }
}
